<template>
  <div id="myApp" :class="clientWidth <= 1700 ? 'bodyStyle2' : 'bodyStyle'">
    <div class="dormitory-z-box">
      <div class="breadcrumb">
        <Breadcrumb>
          <!-- <Breadcrumb.Item class="router-right" @click="toLeve('/')">首页 /</Breadcrumb.Item> -->
          <Breadcrumb.Item v-for="(item, index) of breadcrumbs" :key="index">
            <span class="router-right" @click="toLeve(item.path, index, item)">
              {{ item.name }}</span
            >
          </Breadcrumb.Item>
        </Breadcrumb>
      </div>
      <a-config-provider
        :get-popup-container="getPopupContainer"
        :locale="zhCN"
        prefix-cls="micro-dormitory"
      >
        <router-view />
      </a-config-provider>
    </div>
  </div>
</template>

<script setup>
import zhCN from 'ant-design-vue/es/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
// import axios from 'axios';
import { onMounted, watch, ref, nextTick, computed } from '@vue/runtime-core';
// import { login } from '@/api/common';
import {
  getUserInfo,
  getHeadTeacherClassList,
  checkCurrentUserIsAdmin,
  getCustomizedStatus
} from '@/api/common';
import { ConfigProvider, Breadcrumb } from 'ant-design-vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore();
// 获取当前路由  route.path
const route = useRoute();
const router = useRouter();
const breadcrumbs = ref([]); // 面包屑

const clientWidth = ref();
const getRuleRouter = computed(() => {
  // 返回的是ref对象
  return store.state.user.ruleRouter;
});
onMounted(async () => {
  clientWidth.value = document.body.clientWidth;
  // 监听窗口大小
  window.onresize = () => {
    return (() => {
      clientWidth.value = document.body.clientWidth;
    })();
  };
  init();

  if (window.__MICRO_APP_ENVIRONMENT__) {
    window.microApp.addGlobalDataListener(({ data, methods, appName } = {}) => {
      console.log('全局监听theme', data, methods, appName);
      console.log('全局监听themeooooooo', appName);
      if (appName === 'microBaseApp') {
        window.$microAppMethods = methods;
        // 接受的主题颜色
        if (data.primaryColor) {
          ConfigProvider.config({
            theme: {
              primaryColor: data.primaryColor
            }
          });
        }
      }
    }, true);
  }
});
console.log(clientWidth.value, 'clientWidth');
watch(
  () => clientWidth.value,
  val => {
    console.log(clientWidth.value, '````````````');
  }
);

function init() {
  breadcrumbs.value = route.matched.filter(res => {
    return res.name !== '';
  });
  console.log(breadcrumbs.value);
  console.log('router信息', route);
  // current.value = [breadcrumbs.value[breadcrumbs.value.length - 1].path];
}
// 监听当前路由的变化路由、深度监听等
watch(
  () => route.matched,
  val => {
    let Arr = route.matched.filter(res => {
      return res.name !== '';
    });
    // setTimeout(() => {
    if (route.matched.length !== 1) {
      breadcrumbs.value = Arr;
    } else {
      let arr = breadcrumbs.value.map(x => x.path);
      if (arr.indexOf(Arr[0].path) === -1) {
        breadcrumbs.value = [...breadcrumbs.value, ...Arr];
      }
      if (breadcrumbs.value.length !== 1) {
        let cache = [];
        let a = JSON.stringify(breadcrumbs.value, function (key, value) {
          if (typeof value === 'object' && value !== null) {
            if (cache.indexOf(value) !== -1) {
              // Circular reference found, discard key
              return;
            }
            // Store value in our collection
            cache.push(value);
          }
          return value;
        });
        cache = null; // E
        localStorage.setItem('MENU_PATH', a);
      } else {
        breadcrumbs.value = JSON.parse(localStorage.getItem('MENU_PATH'));
      }
    }
    // }, 100);
  }
);
watch(
  getRuleRouter,
  (newVal, oldVal) => {
    console.log('lorem---------------------newVal, oldVal', newVal, oldVal);
    console.log('啊哈哈---', route);
    // if (route.fullPath.value === '/ruleSetting') {
    if (newVal[1] && newVal[1].name === '规则设置') {
      breadcrumbs.value = newVal;
      console.log('去规则设置');
      // let accessControl = store.state.user.accessControl;
      // if (accessControl * 1 === 1) {
      //   store.commit('user/setAccessControlTwo', 1);
      // }
      store.commit('user/setDoorRule', 0);
    }
    if (newVal[2] && newVal[2].name === '宿舍门禁规则') {
      console.log('宿舍门禁规则');
      store.commit('user/setAccessControl', 1);
      // store.commit('user/setAccessControlTwo', 0);
      store.commit('user/setDoorRule', 1);
    }
    // if (newVal[1] && newVal[1].name === '宿舍考核规则') {
    //   breadcrumbs.value = newVal;
    // }
    // }
  },
  { immediate: true, deep: true }
);
// ------
function toLeve(value, index, data) {
  let pathVal = [];
  pathVal = store.state.user.ruleRouter;
  if (pathVal.length === 3 && pathVal[2].isAttendance) {
    let ruleVal = JSON.parse(sessionStorage.getItem('ruleList'));
    let ruleLists = JSON.parse(sessionStorage.getItem('newRuleList'));
    store.commit('user/updateSignList', true);

    console.log(JSON.stringify(ruleVal) === JSON.stringify(ruleLists), '*********//');
    if (JSON.stringify(ruleVal) === JSON.stringify(ruleLists)) {
      router.push({
        path: value
      });
      if (data.status === 0) {
        store.commit('user/setRuleStatus', -1);
        store.commit('user/setRuleRouter', [
          {
            name: '首页',
            path: '/admin/usersInfo'
          },
          {
            name: '规则设置',
            path: '/ruleSetting'
          }
        ]);
      }
      if (route.path === value) return false;
      if (data.meta.isShow) breadcrumbs.value.splice(index);
    } else {
      // isLeaveRoute.value = true;
      store.commit('user/updateIsShowModal', true);
    }
  } else {
    router.push({
      path: value
    });
    if (data.status === 0) {
      store.commit('user/setRuleStatus', -1);
      store.commit('user/setRuleRouter', [
        {
          name: '首页',
          path: '/admin/usersInfo'
        },
        {
          name: '规则设置',
          path: '/ruleSetting'
        }
      ]);
    }
    if (route.path === value) return false;
    if (data.meta.isShow) breadcrumbs.value.splice(index);
  }
}
dayjs.locale('en');

// function getPopupContainer(el, dialogContext) {
//   if (dialogContext) {
//     return dialogContext.getDialogWrap();
//   } else {
//     return document.body;
//   }
// }
function getPopupContainer(el, dialogContext, triggerNode) {
  if (triggerNode) {
    return triggerNode.parentNode;
  }
  if (el) {
    return el.parentNode;
  }
  if (dialogContext) {
    return dialogContext.getDialogWrap();
  }
  if (!window.__MICRO_APP_ENVIRONMENT__) {
    return document.body;
  }
  return el ?? document.body ?? triggerNode;
}
function hexToRgba() {
  let color = store.state.user.primaryColor.slice(1); // 去掉'#'号
  let number = 0.6;
  let rgba = [
    parseInt('0x' + color.slice(0, 2)),
    parseInt('0x' + color.slice(2, 4)),
    parseInt('0x' + color.slice(4, 6)),
    1 - number
  ];
  return 'rgba(' + rgba.toString() + ')';
}

let stateUserData = ref({});
async function getDataFunc() {
  let userState = '';
  let identities = [];

  let state = {
    userInfo: {},
    identity: '',
    menu: [
      {
        path: '/admin',
        name: '住宿管理',
        children: [
          { path: '/admin/usersInfo', name: '学生信息管理' },
          { path: '/admin/teacherInfo', name: '教职工信息管理' },
          { path: '/admin/classInfo', name: '班级信息管理' },
          { path: '/admin/dormitoryManage', name: '宿舍楼管理' },
          { path: '/admin/roomManage', name: '房间管理' }
        ]
      },
      {
        path: '/check',
        name: '考核查询',
        breadcrumbName: '考核查询',
        children: [
          { path: '/check/dormitoryPersonal', name: '宿舍个人考核' },
          { path: '/check/dormitoryCollective', name: '宿舍集体考核' },
          { path: '/check/classCollective', name: '班级集体考核' },
          { path: '/check/inspect', name: '检查记录' }
        ]
      },
      {
        path: '/ruleSetting',
        name: '规则设置'
      },
      {
        path: '/extern',
        name: '走读管理'
      },
      {
        path: '/jurisdiction',
        name: '权限管理'
      }
    ],
    classInfoList: []
  };
  // ------
  state.userInfo = userState;
  let isAdmin = false;
  let appId = sessionStorage.getItem('appId') ? sessionStorage.getItem('appId') : 0;
  await getHeadTeacherClassList().then(res => {
    if (res.data.code === 200) {
      if (res.data.data) {
        state.classInfoList = res.data.data;
      }
    }
  });
  // 获取 allUser信息
  await getUserInfo({}).then(res => {
    if (res.data.code === 200) {
      identities = res.data.data.identities;
    }
  });
  await checkCurrentUserIsAdmin(appId).then(res => {
    if (res.data.code === 200) {
      isAdmin = res.data.data;
      if (isAdmin === true) {
        localStorage.setItem('dormitoryIsAdmin', 0);
      } else {
        localStorage.setItem('dormitoryIsAdmin', 1);
      }
    }
  });
  // 看是不是兴隆校区
  await getCustomizedStatus().then(res => {
    if (res.data.code === 200) {
      if (res.data.data.currentIsXingLong === true) {
        localStorage.setItem('localStorageSchoolId', '346001568933441537');
      } else {
        localStorage.setItem('localStorageSchoolId', '1');
      }
    } else {
      localStorage.setItem('localStorageSchoolId', '1');
    }
  });

  // 新版本
  if (identities.indexOf(3) > -1 || isAdmin) {
    state.identity = 8;
  }
  // 新版本
  if (identities.indexOf(3) <= -1 && !isAdmin) {
    console.log('----------------------------------------------------------------lorem');
    state.identity = 2;
    let list = [];
    state.menu.forEach(v => {
      if (['/extern', '/ruleSetting', '/jurisdiction'].indexOf(v.path) === -1) {
        list.push(v);
      }
    });
    state.menu = list;
    state.menu.forEach(v => {
      if (v.path === '/check') {
        v.children = v.children.filter(x => x.path !== '/check/inspect');
      }
    });
    state.menu.forEach(v => {
      if (v.path === '/admin') {
        let arr = [];
        v.children.forEach(v => {
          if (
            ['/admin/dormitoryManage', '/admin/roomManage', '/admin/teacherInfo'].indexOf(
              v.path
            ) === -1
          ) {
            arr.push(v);
          }
        });
        v.children = arr;
      }
    });
  }
  store.commit('user/setState', state);
  console.log(state, '*******state');
  if (state.classInfoList.length === 0) {
    breadcrumbs.value = [];
    router.push('/error');
  }
  stateUserData.value = state;
  router.beforeEach((to, from, next) => {
    console.log(to);
    console.log(from);
    const stateUser = stateUserData.value;
    if (to.path === '/error') {
      return next();
    }
    if (!stateUser && to.path !== '/admin/usersInfo') {
      if (to.path === '/error') {
        console.log('放行2');
        next();
      } else {
        // 如果用户不存在，并且访问的页面不是首页，就前往首页
        next('/admin/usersInfo');
      }
    } else {
      console.log('放行2', stateUser.identity);
      console.log(stateUser.classInfoList);
      // 如果是管理员权限则可进入 8是管理员
      if (stateUser.identity === 8) {
        next();
      } else {
        if (!stateUser.classInfoList.length) {
          next('/error');
        } else {
          next();
        }
      }
    }
  });
}
getDataFunc();

ConfigProvider.config({
  getPopupContainer
});
// 定义颜色变量
const setStyles = computed(() => {
  return {
    '--primaryColor': store.state.user.primaryColor,
    primaryColor: store.state.user.primaryColor
  };
});
const setStyles1 = computed(() => {
  return {
    '--primaryColor1': hexToRgba(),
    primaryColor1: hexToRgba()
  };
});
const setPrimaryColor = computed(() => store.state.user.primaryColor);
</script>

<style lang="less">
// -------------------------------------------------------------------------------------------
// .micro-dormitory-menu-submenu-selected {
//   color: var(--van-primary-color-web) !important;
// }
// .micro-dormitory-pagination-item:hover a {
//   color: var(--van-primary-color-web) !important;
// }
// .micro-dormitory-pagination-item:hover {
//   border-color: var(--van-primary-color-web) !important;
// }
// .micro-dormitory-select:not(.micro-dormitory-select-disabled):hover
//   .micro-dormitory-select-selector {
//   border-color: var(--van-primary-color-web) !important;
// }
// .micro-dormitory-pagination-options-quick-jumper input:hover {
//   border-color: var(--van-primary-color-web) !important;
// }
// .micro-dormitory-menu-item a:hover {
//   color: var(--van-primary-color-web) !important;
// }
// .micro-dormitory-pagination-item-active {
//   border-color: var(--van-primary-color-web) !important;
// }
// .micro-dormitory-input-affix-wrapper:not(.micro-dormitory-input-affix-wrapper-disabled):hover {
//   border-color: var(--van-primary-color-web) !important;
// }
// .micro-dormitory-btn-primary:not(.micro-dormitory-btn-background-ghost) {
//   border-color: var(--van-primary-color-web) !important;
//   background: var(--van-primary-color-web) !important;
// }
// -------------------------------------------------------------------------------------------
#app {
  width: 100%;
  min-width: 1440px;
  // min-height: 100vh;
  min-height: 700px;
  background: #f2f2f2;
  font-family: Source Han Sans CN, Source Han Sans CN-400;
}

.custom-options-dialog-box .btn-cancel {
  color: #999999;
}
.micro-dormitory-btn.micro-dormitory-btn-primary:not(.micro-dormitory-btn-background-ghost):focus {
  color: #fff !important;
}
.micro-dormitory-btn.micro-dormitory-btn-primary:not(.micro-dormitory-btn-background-ghost):hover {
  color: #fff !important;
}
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}
.bodyStyle3 {
  flex: 1;
  padding: 0px 120px 24px;
}
.bodyStyle {
  width: 100%;
  padding: 0px 120px 24px;
}
.bodyStyle2 {
  width: 100%;
  padding: 0px 120px 24px;
}
.breadcrumb {
  padding-bottom: 14px;
  background: #f2f2f2;
  cursor: pointer;
}
/*定义滚动条轨道 内阴影+圆角*/
::-webkit-scrollbar-track {
  border-radius: 10px;
  background-color: rgba(0, 0, 0, 0.1);
}

/*定义滑块 内阴影+圆角*/
::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
  background-color: rgba(0, 0, 0, 0.1);
}
/deep/.micro-dormitory-cascader-picker:hover .micro-dormitory-cascader-picker-clear {
  color: rgba(0, 0, 0, 0.25) !important;
}

///

/deep/.micro-dormitory-btn-primary {
  background: var(--van-primary-color-web) !important;
  border-color: var(--van-primary-color-web) !important;
}
/deep/.micro-dormitory-btn-background-ghost {
  border-color: var(--van-primary-color-web) !important;
  color: var(--van-primary-color-web) !important;
  background: none !important;
}

/deep/.micro-dormitory-btn-primary[disabled],
/deep/.micro-dormitory-btn-primary[disabled]:hover,
/deep/.micro-dormitory-btn-primary[disabled]:focus,
/deep/.micro-dormitory-btn-primary[disabled]:active {
  // color: rgba(0, 0, 0, 0.25) !important;
  // background: #f5f5f5 !important;
  // border-color: #d9d9d9 !important;
  color: #fff !important;
  background: #e6e6e6 !important;
  border-color: #e6e6e6 !important;
  text-shadow: none !important;
  box-shadow: none !important;
}
/deep/.micro-dormitory-btn-background-ghost:hover,
/deep/.micro-dormitory-btn-background-ghost:focus {
  background-color: #fff !important;
  border-color: var(--van-primary-color-web) !important;
}

/deep/.micro-dormitory-menu-item a:hover {
  color: var(--van-primary-color-web) !important;
}
/deep/.micro-dormitory-menu-submenu-selected {
  color: var(--van-primary-color-web) !important;
}

// /deep/.micro-dormitory-menu-item a:hover{
// color: var(--van-primary-color-web) !important;
// }
/deep/.micro-dormitory-input-affix-wrapper:focus {
  border-color: var(--van-primary-color-web) !important;
}
/deep/input[type='checkbox']:checked {
  background: var(--van-primary-color-web) !important;
}
.search-png {
  width: 17px;
  height: 17px;
}
.micro-dormitory-table-tbody > tr.micro-dormitory-table-row-selected > td {
  background: #fff !important;
}
.micro-dormitory-btn.micro-dormitory-btn-background-ghost.btn-global-green-ghost {
  color: #56d6b7 !important;
  border: 1px solid #56d6b7 !important;
}
.micro-dormitory-btn.micro-dormitory-btn-background-ghost.btn-global-green-ghost:hover {
  color: #56d6b7 !important;
  border: 1px solid #56d6b7 !important;
}
.micro-dormitory-btn.micro-dormitory-btn-background-ghost.btn-global-green-ghost:focus {
  border: 1px solid #56d6b7 !important;
}
.z-green-color {
  color: #56d6b7 !important;
}
.new-icon-arrow {
  // border: 1px solid #f00;
  display: flex;
  align-items: center;
}
.micro-dormitory-pagination-item-link {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}
.micro-dormitory-select-arrow {
  // border: 1px solid #f00;
  position: absolute !important;
  top: 0 !important;
  bottom: 0 !important;
  margin: auto !important;
  display: flex;
  align-items: center;
}
.micro-dormitory-pagination-item-active {
  background: var(--van-primary-color-web) !important;
  color: #fff !important;
  a {
    color: #fff !important;
  }
}
.micro-dormitory-pagination-item-active:hover {
  border: 1px solid var(--van-primary-color-web) !important;
}
.zz-global-nodata {
  // border: 1px solid #f00;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 60vh;
  img {
    width: 300px;
    height: 300px;
  }
}
.more-new {
  width: 35px;
  height: 35px;
}
// .micro-dormitory-menu-submenu-title:hover .micro-dormitory-menu-submenu-arrow {
//   color: #333333 !important;
// }

// .micro-dormitory-menu-submenu-selected .micro-dormitory-menu-submenu-arrow {
//   color: var(--van-primary-color-web) !important;
// }
// .micro-dormitory-menu-submenu:not(.micro-dormitory-menu-submenu-open):hover
//   .micro-dormitory-menu-submenu-arrow {
//   color: #333333 !important;
// }
// .micro-dormitory-select-item.micro-dormitory-select-item-option:hover {
//   background-color: var(--van-primary-color-web) !important;
//   color: #fff !important;
// }
// .micro-dormitory-cascader-menu-item:hover {
//   background-color: var(--van-primary-color-web) !important;
//   color: #fff !important;
//   .micro-dormitory-cascader-menu-item-expand-icon {
//     color: #fff !important;
//   }
// }

// .h-58-new /deep/.micro-dormitory-checkbox-wrapper:hover {
//   background-color: var(--van-primary-color-web) !important;
//   color: #fff !important;
// }
// .object-change-down .micro-dormitory-checkbox-wrapper:hover {
//   background-color: var(--van-primary-color-web) !important;
//   color: #fff !important;
// }
// .micro-dormitory-select-item.micro-dormitory-select-item-option.micro-dormitory-select-item-option-active.micro-dormitory-select-item-option-selected {
//   background-color: var(--van-primary-color-web) !important;
//   color: #fff !important;
// }
// ----------------------------------------------------------------------
// .object-change-down .micro-dormitory-checkbox-wrapper-checked {
//   background-color: var('setStyles1.primaryColor1') !important;
//   color: #fff !important;
// }
// -----------------------------
.bedchoice-dialog-box {
  .micro-dormitory-menu-item .micro-dormitory-radio-wrapper {
    height: auto !important;
    align-items: flex-start !important;
    line-height: 21px !important;
  }
}
</style>
<style lang="less">
::v-deep(.anticon-down.micro-dormitory-select-suffix) {
  vertical-align: top !important;
}
::v-deep(span.anticon:not(.app-iconify)) {
  vertical-align: baseline !important;
}
::v-deep(.micro-dormitory--select .micro-dormitory--select-arrow) {
  > span {
    vertical-align: top !important;
  }
}

.micro-dormitory-message .anticon {
  vertical-align: text-top !important;
}

.micro-dormitory-message .anticon {
  vertical-align: middle !important;
  top: -1px;
}
.micro-dormitory-tabs-dropdown {
  display: none !important;
}
</style>
